package com.juno.cafenoa.member;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.juno.cafenoa.Constants;
import com.juno.cafenoa.MainActivity;
import com.juno.cafenoa.R;
import com.juno.cafenoa.TopNavigatorView;
import com.juno.cafenoa.R.id;
import com.juno.cafenoa.R.layout;
import com.juno.cafenoa.mypage.PasswordActivity;
import com.juno.cafenoa.net.AsyncTaskCompleteListener;
import com.juno.cafenoa.net.HttpPostTask;
import com.juno.cafenoa.sqlite.CafeNoaDBAdapter;
import com.juno.cafenoa.util.CafeNoaPreference;
import com.juno.cafenoa.util.Util;

/**
 * 로그인 액티비티. 로그인을 위한 id, password를 입력하는 activity
 * @author JUNHO
 *
 */
public class LoginActivity extends Activity implements OnClickListener, OnTouchListener{
	EditText etID;
	EditText etPass;
	
	Button btnLogin;
	Button btnRegedit;
	
	Context mContext;
	
	TopNavigatorView navi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		mContext = this;
		etID = (EditText) findViewById(R.id.login_id);
		etPass = (EditText)findViewById(R.id.login_password);
		btnLogin = (Button) findViewById(R.id.login_btn);
		btnRegedit = (Button) findViewById(R.id.login_member_regedit_btn);
		//상단바 text login으로교체 
		navi = (TopNavigatorView) findViewById(R.id.navi_login);
		navi.init("Login");
		
		//password같은경우 action_down시 password activity로 열음.
		etPass.setOnTouchListener(this);
		
		btnLogin.setOnClickListener(this);
		btnRegedit.setOnClickListener(this);
		
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(v==etPass && event.getAction()==MotionEvent.ACTION_DOWN){
			//패스워드  EditText 터치시.
			//password 입력하는 activity로 전환
			Intent intent = new Intent(mContext, PasswordActivity.class);
			intent.putExtra(Constants.USER_PASSWORD_MODE_SET, Constants.PASSWORD_SET_LONGIN);
			startActivityForResult(intent, Constants.REQUEST_PASSWORD_SET);
		}
		return false;
	}
	@Override
	public void onClick(View v) {
		if(v==btnLogin){
			if(etID.getText().equals("")){
				Toast.makeText(mContext, "아이디가 입력되지 않았습니다", Toast.LENGTH_SHORT).show();
			} else if(etPass.getText().equals("")){
				Toast.makeText(mContext, "패스워드가 입력되지 않았습니다", Toast.LENGTH_SHORT).show();
			} else {
				//서버와 통신하여 가져옴.
				loginListener.excuteHttpTask();
			}
		} else if(v==btnRegedit){
			Intent intent = new Intent(mContext, AccountMakeActivity.class);
			mContext.startActivity(intent);
			finish();
		}
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode== Constants.REQUEST_PASSWORD_SET && resultCode==Constants.REQUEST_PASSWORD_SET){
			//password_activity 이후 4자리 값을 받아옴.
			String passwd = data.getExtras().getString(Constants.USER_PASSWORD_STRING);
			etPass.setText(passwd);
		}
	}
	
	
	/**
	 * login할때 필요한 async task를 위한 리스너.
	 */
	AsyncTaskCompleteListener loginListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			//Url 세팅.
			String url = Util.getUrl("MemberLogin");
			
			//id와 passwd 세팅해줌.
			String id = etID.getText().toString();
			String passwd = etPass.getText().toString();
			Log.d("KYT", "GCM ID = "+CafeNoaPreference.getGcmID(mContext));
			//name value pair에 id와 password 세팅
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("USER_ID", id));
			value.add(new BasicNameValuePair("USER_PASSWORD", passwd));
			value.add(new BasicNameValuePair("USER_GCM_ID", CafeNoaPreference.getGcmID(mContext)));
			//httpPostTast 실행.
			HttpPostTask http = new HttpPostTask(mContext, value, url, loginListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			//http 통신 실행후 서버로부터 오는 내용.
			//작업이 모두 완료되었다면.
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				String resultString = null;
				int point = 0;
				String userGrade = null;
				int dbVersion = -1;
				try {
					//코드 받아옴. JSON형태.
					//파싱하는 과정
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");
					resultString = object.getString("RESULT_STRING");
					point = object.getInt("USER_POINT");
					userGrade = object.getString("USER_GRADE");
					dbVersion = object.getInt("DB_VERSION");
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//코드가 내려오지 않은경우는 서버 에러 !
				if(code==-1){
					Log.v("CafeNoa","Server Error No code!");
					return;
				}
				
				if(code==Constants.NETWORK_SUCCESS){
					//받아온 id, passwd값 프리퍼런스에 저장.
					String id = etID.getText().toString();
					String passwd = etPass.getText().toString();
					Log.v("currentPoint","point" + point);
					
					//서버와 통신 성공시 프리퍼런스로 아이디를 저장함.
					CafeNoaPreference.setUserID(mContext, id);
					CafeNoaPreference.setUserPassword(mContext, passwd);
					CafeNoaPreference.setUserPoint(mContext, point);
					CafeNoaPreference.setUserGrade(mContext, userGrade);
					CafeNoaPreference.setDBVersion(mContext, String.valueOf(dbVersion));

					Log.v("CafeNoa","Save User Inform to Preference");
					
					Intent intent = new Intent(mContext, MainActivity.class);
					mContext.startActivity(intent);
					finish();
				} else{ 
					if(code == Constants.ID_LOGIN_ERROR)
						Toast.makeText(mContext, "일치하는 아이디가 존재하지 않습니다.", Toast.LENGTH_SHORT).show();
					else if(code == Constants.PASSWORD_LOGIN_ERROR)
						 Toast.makeText(mContext, "일치하는 패스워드가 존재하지 않습니다.", Toast.LENGTH_SHORT).show();
					etID.setText("");
					etPass.setText("");
				}
			}
		}
		
	};
	
	
}